# 数据写入数据库的相关操作
import logging
import pymssql
# 连接
logging.basicConfig(
    filename='logging.txt',
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)


def connection(imglink, title, titlelink, address, housedescribe, label, price, squareprice, housinginformation, jiaoyi, k, i):
    conn = pymssql.connect(
        server='DESKTOP-2NR5UU8',
        user='abc',
        password='123456',
        database='python',
        charset='UTF-8',
        as_dict=True  # 返回字典形式的行
    )
    #创建游标
    cursor = conn.cursor()
    from lxml import etree
    sql = (f"INSERT INTO lianjia (图片链接, 房名, 房屋介绍链接, 地址, 房屋描述, 标签, 价格, 平方价, 房屋属性, 交易属性) VALUES (N'{imglink}',N'{title}',N'{titlelink}',N'{address}',N'{housedescribe}',N'{label}',N'{price}',N'{squareprice}',N'{housinginformation}',N'{jiaoyi}')")
    try:
        cursor.execute(sql)
        logging.info(f'插入数据成功！！房屋名称：{title}')
    except Exception as e:
        logging.error(f'存储数据出错！！url：{titlelink}, error: {e}, sql: {sql}')
        print("第{}页第{}条数据抓取失败!".format(k, i))
    conn.commit()
    conn.close()

